package com.cf.utils;

import com.cf.domain.vo.UserVO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author lzqinga@126.com
 * @Date 2024/12/7  9:40
 */
public class RequestUtil {

    // 获取当前请求的IP地址，如果无法获取则返回默认值（比如"unknown"）
    public static String getIpAddress(HttpServletRequest request) {
        try {
            String ip = request.getHeader("X - Forwarded - For");
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy - Client - IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL - Proxy - Client - IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            return ip;
        } catch (Exception e) {
            return "unknown";
        }
    }

    // 通过Session获取用户的标识符（这里以用户名为例，实际可根据存储在Session中的具体用户信息调整）
    public static String getUserIdentifier(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session!= null) {
            UserVO userVO = (UserVO) session.getAttribute("user");
            if (userVO!= null) {
                return userVO.getId() + "";
            }
        }
        return "游客";
    }
}
